'use strict';
var _ = require('lodash');
var Helper = require('../lib/helper');
var Task = require('../models/task');
var TaskItem = require('../models/taskItem');
var moment = require('moment');
var thunkify = require('thunkify');
var fs = require('fs');
var readFile = thunkify(fs.readFile);
var unlink = thunkify(fs.unlink);
var exists = thunkify(fs.exists);

module.exports.add = function *(next){
  if(!Helper.isLogin(this)){
    this.redirect('/admin/login');
  }
  var user_id = Helper.getLoginUID(this);
  yield this.render('admin/task/add',{'title':'发布任务'});
};

/**
 * 添加任务
 * @yield {[type]} [description]
 */
module.exports.doAdd = function *(){
  if(!Helper.isLogin(this)){
    this.redirect('/admin/login');
  }
  var user_id = Helper.getLoginUID(this);

  var formData = this.request.body;

  console.log('formData:',formData);
  if(!formData['name']){
    this.flash.error = '任务名称不能为空！';
    return this.redirect('/admin/task/add');
  }

  var task = new Task({
    'name':formData['name'] || '',
    'description':formData['description'] || '',
    'demand':formData['demand'] || '',
    'user_id':user_id,
    'date':formData['date'] || moment().format('YYYY-MM-DD')
  });

  var res = yield task.save();

  var memberName = formData['memberName'];
  var memberContent = formData['memberContent'];
  if(_.size(memberName)){
    var i = 0;
    var name;
    var content;

    while(name = memberName[i]){
      content = memberContent[i];
      var taskItem = new TaskItem({
        'name':name,
        'content':content,
        'task_id':res.attributes._id
      });
      var save_res = yield taskItem.save();
      i++;
    }
  }

  if(res){
    this.flash.success = '创建任务成功！';
    this.redirect('/admin');
  }
};

module.exports.edit = function *(next){

  yield this.render('admin/task/edit');
};

/**
 * 删除任务
 * @param {Function} next          [description]
 * @yield {[type]}   [description]
 */
module.exports.delete = function *(next){

  var params = this.params;
  if(!_.has(params,'id')){
    return this.body = {'success':false,'msg':'请求失败!'};
  }

  var task = yield Task.where('_id',params['id']).findOne();
  var task_item = yield TaskItem.where('task_id',task.attributes._id).find();
  
  var item;
  var i = 0;
  while(item = task_item[i]){
    if(!item.attributes.image_url){
      i++;
      continue;
    }

    if(item.attributes.image_url.startsWith('/upload')){
      var file_path = __dirname + '/../static'+item.attributes.image_url;

      var exists_res = yield Helper.existsFile(file_path);
      
      if(exists_res['success']){
        try{
          yield unlink(file_path);
        }catch(error){

        }
      }
      
    }else if(item.attributes.image_url.startsWith('huanping')){
      try{
        yield Helper.deleteQiniuFile(item.attributes.image_url);
      }catch(error){

        // return this.throw(error);
      }
    }

    i++;
  }

  yield Task.where('_id',params['id']).remove();
  yield TaskItem.where('task_id',task.attributes._id).remove();

  this.body = {'success':true};

};

module.exports.group = function *(){
  var args = this.params;

  if(!args.date){
    this.flash.error = '参数不能为空！';
  }else{
    this.flash.error = '';
  }

  var res = yield Task.where('date',args.date).sort({'_id':-1}).find();
  if(!_.size(res)){
    this.flash.error = '查看的任务不存在！';
  }else{
    var i = 0;
    var task_item;
    var task_tmp = [];
    while(task_item = res[i]){
      task_item['list'] = yield TaskItem.where('task_id',task_item.attributes._id).find();
      task_tmp.push(task_item);
      i++;
    }
  }

  yield this.render('task/group',{'date':args.date,'task':task_tmp,'title':args.date + '任务安排'});

};

module.exports.detail = function *(next){
  var ObjectID = require('mongodb').ObjectID;
  var args = this.params;

  if(!args.id){
    this.flash.error = '参数不能为空！';
  }else{
    this.flash.error = '';
  }

  var res = yield Task.where('_id',args.id).findOne();

  if(!res){
    this.flash.error = '查看的任务不存在！';
  }else{
    res['list'] = yield TaskItem.where('task_id',res.attributes._id).find();
  }

  yield this.render('task/detail',{'title':res.attributes.name,'task':res});
};

/**
 * 上传图片
 * @yield {[type]} [description]
 */
module.exports.uploadImage = function *(){
  var args = this.params;
  var params = this.request.body;
  if(!args.id){
    this.body = {'success':false,'message':'传递参数错误！'};
  }

  var parse = require('co-busboy');
  var path = require('path');
  var fs = require('fs');
  var os = require('os');
  // multipart upload
  var parts = parse(this);
  var part;
  var upload_res;

  var filename = 'huanping_'+args.id+'.png';
  while (part = yield parts) {
    yield this.save(part,__dirname + '/../static/upload/'+filename);
    var image_res = yield readFile(__dirname + '/../static/upload/'+filename);
    yield unlink(__dirname + '/../static/upload/'+filename);

    //上传流文件
    var upload_res = yield Helper.qiniuUploadImage(image_res,filename);
  }

  var task_item = yield TaskItem.where('_id',args.id).findOne();
  task_item.set('image_url',filename);
  task_item.set('complete',true);
  yield task_item.save();

  this.body = {'success':true,'message':'上传成功','path':'http://7u2r0u.com2.z0.glb.qiniucdn.com/'+filename+'?t='+Math.random(),'id':args.id};
};
